package com.beidouapp.mvc;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;

import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.beidouapp.common.enums.RoleGroupType;
import com.beidouapp.common.util.JSONUtils;
import com.beidouapp.domain.pojo.Employee;
import com.beidouapp.domain.pojo.Organization;
import com.beidouapp.domain.pojo.Resource;
import com.beidouapp.domain.pojo.Role;
import com.beidouapp.domain.pojo.User;
import com.beidouapp.security.model.LoginRequest;
import com.beidouapp.security.model.ReturnDataInfo;
import com.beidouapp.security.model.SessionUser;
import com.beidouapp.security.mvc.constant.SessionConstants;
import com.beidouapp.security.utils.DscpCommUtils;
import com.beidouapp.service.EmployeeService;
import com.beidouapp.service.OrganizationService;
import com.beidouapp.service.ResourceService;
import com.beidouapp.service.RoleService;
import com.beidouapp.service.UserService;
import com.beidouapp.utils.UIUtils;

@Controller
public class SessionController {
	private static final Logger logger = LoggerFactory.getLogger(SessionController.class);

	@Autowired
	private UserService userSerivce;

	@Autowired
	private OrganizationService organizationService;

	@Autowired
	private EmployeeService employeeService;

	@Autowired
	private RoleService roleService;

	@Autowired
	private ResourceService resourceService;
	
	/*@Autowired
	private SSOExecuterService ssoExecuterService;
	
	@Autowired
	private ContactsService contactsService;*/

	
	@RequestMapping(value = "session/login", method = RequestMethod.POST)
	public @ResponseBody ReturnDataInfo<SessionUser> adminLogin(@RequestBody LoginRequest user,
			@RequestHeader(defaultValue = "-480", required = false, value = "GMTOffset") String userGMTOffset,
			@RequestHeader(defaultValue = "800", required = false, value = "TimezoneOffset") int userTimezoneOffset,
			HttpSession session, HttpServletRequest request) throws IOException {
			return loginByPlat(user,session);
	}
	
	@RequestMapping(value = "isLogin", method = RequestMethod.GET)
	public @ResponseBody ReturnDataInfo<SessionUser> isLogin(
			@RequestHeader(defaultValue = "-480", required = false, value = "GMTOffset") String userGMTOffset,
			@RequestHeader(defaultValue = "800", required = false, value = "TimezoneOffset") int userTimezoneOffset,
			HttpSession session, HttpServletRequest request) throws IOException {
		  if(DscpCommUtils.getSessionUser(session)!=null){
			 return  ReturnDataInfo.createSuccessfulSingleExecuteResult(DscpCommUtils.getSessionUser(session));
		  }else{
			 return  ReturnDataInfo.createFailedExecuteResult(503, null);
		  }
			  
	}
	
	
	
	
	private ReturnDataInfo<SessionUser> loginByPlat(LoginRequest user,HttpSession session){
		session.removeAttribute(SessionConstants.SESSION_DSCP_USER_OBJECT);
		logger.debug("用户登录:" + user.getLoginName());
		User userInfo = userSerivce.getUserWithNameAndPassword(user.getLoginName(), user.getPassword());
		logger.debug("用户登录结束,用户名和密码是否正确" + userInfo);
		if (userInfo == null) {
			extendAudiLog(user.getLoginName());
			return ReturnDataInfo.createFailedExecuteResult("用户名或密码不正确");
		}
		SessionUser sUser = new SessionUser();
		sUser.setUserId(userInfo.getId());
		sUser.setLoginname(userInfo.getLoginName());
		if (userInfo.getId() != null) {
			Employee employee = employeeService.getEmployeeByUserId(userInfo.getId());
			if (employee == null) {
				logger.warn("user {} is not found employee info.", userInfo.getId());
				return ReturnDataInfo.createFailedExecuteResult("用户无权限.");
			}
			sUser.setUserName(employee.getEmpName());
			sUser.setEmpId(employee.getId());
			sUser.setEmpAddress(employee.getHomeAddress());
			Organization organization = organizationService.getOrganizationById(employee.getOrgId());
			if (organization != null) {
				sUser.setOrgId(organization.getId());
				sUser.setOrgName(organization.getName());
				sUser.setOrgCode(organization.getCode());
			}

			List<Role> roles = roleService.findRolesByEmpId(employee.getId());
			for (Role role : roles) {
				sUser.setRoleId(role.getId());
				sUser.setRoleGroupId(role.getRoleGroupId());
				sUser.setRoleStatus(role.getStatus());
				List<Resource> hold_resources = null;
				if (role.getRoleGroupId() != null && role.getRoleGroupId() == RoleGroupType.PLAT_ROLE.getCode()) {
					hold_resources = resourceService.findAllResource();
				} else {
					hold_resources = resourceService.findRoleResourcesByRoleId(role.getId());
				}
				if (hold_resources != null) {
					List<String> codes = new ArrayList<String>();
					for (Resource rc : hold_resources) {
						codes.add(rc.getCode());
					}
					sUser.setResourceCodes(codes);
				}
				break;
			}
		}
		DscpCommUtils.setSessionUser(session, sUser);
		UIUtils.setSessionUser(sUser);
		return ReturnDataInfo.createSuccessfulSingleExecuteResult(sUser);
	}

	
	private  void extendAudiLog(String loginName){
		User userInfo1 = userSerivce.getUserWithName(loginName);
		if(userInfo1!=null){
			Employee employee = employeeService.getEmployeeByUserId(userInfo1.getId());
			if(employee!=null){
				SessionUser sUser = new SessionUser();
				sUser.setUserId(userInfo1.getId());
				sUser.setLoginname(userInfo1.getLoginName());
				sUser.setUserName(employee.getEmpName());
				Organization organization = organizationService.getOrganizationById(employee.getOrgId());
				if (organization != null) {
					sUser.setOrgId(organization.getId());
					sUser.setOrgName(organization.getName());
					sUser.setOrgCode(organization.getCode());
				}
				UIUtils.setSessionUser(sUser);
			}
		}
	}

	@RequestMapping(value = "/session/loginout", method = RequestMethod.POST)
	public @ResponseBody ReturnDataInfo<String> loginout(HttpSession session) {
		session.invalidate();
		return ReturnDataInfo.createSuccessfulSingleExecuteResult(null);
	}

	// 页面跳转
	@RequestMapping(value = "/tologin", method = RequestMethod.GET)
	public void tologin(HttpServletRequest request,
			HttpServletResponse response) {
		   try {
			response.sendRedirect(request.getContextPath());
		} catch (IOException e) {
		}
	}
	
	@RequestMapping(value = "login", method = RequestMethod.GET)
	public String toAdminlogin() {
		return "login";
	}

	// 页面跳转
	@RequestMapping(value = "/main", method = RequestMethod.GET)
	public String main() {
		return "main";
	}

	/**
	 * 修改登录用户密码页面跳转
	 *
	 * @return
	 */
	@RequestMapping(value = "/session/changepassword", method = RequestMethod.GET)
	public ModelAndView changePasswordPage(HttpSession session) {
		ModelAndView view = new ModelAndView();
		SessionUser sessionUser = DscpCommUtils.getSessionUser(session);
		JSONObject sessionJson = JSONUtils.convert2Obj(sessionUser);
		view.addObject("sUser", sessionJson);
		view.addObject("loginName", sessionUser.getLoginname());
		view.setViewName("user_changePassword");
		return view;
	}

	@RequestMapping(value = "/session/changePassword", method = RequestMethod.POST, headers = "Content-Type=application/json")
	public @ResponseBody ReturnDataInfo<String> changePassword(HttpSession session, HttpServletRequest request,
			@RequestBody Map<String, String> paramters) {
		try {
			SessionUser sessionUser = DscpCommUtils.getSessionUser(session);
			ObjectMapper mapper = new ObjectMapper();
			String userpassword = mapper.convertValue(paramters.get("userpassword"), String.class);
			String oldPassword = mapper.convertValue(paramters.get("oldPassword"), String.class);
			userSerivce.changeUserPassword(sessionUser.getUserId(), sessionUser.getLoginname(), oldPassword,
					userpassword);
			return ReturnDataInfo.createSuccessfulSingleExecuteResult(null);
		} catch (Exception ex) {
			return ReturnDataInfo.createFailedExecuteResult(ex.getMessage());
		}
	}

	 // 页面跳转
    @RequestMapping(value = "/session/employee", method = RequestMethod.GET)
    public String forword2Employee() {
        return "special/special_employee";
    }

}
